<template>
  <KiFormDialog
    :title="formTitle"
    :show.sync="form.show"
    :readonly="form.status==='r'"
    ref="kiFormDialogRef"
    @close="() => { form.show = false }"
    @closed="onClosed"
  >
    <el-steps
      :active="active"
      align-center
    >
      <el-step
        :title="v.title"
        v-for="v of state.steps[state.businessTypeId]"
        :status="active === v.active ? 'finish' : v.status||'wait'"
        :key="v.component"
        @click.native="active = v.active"
      />
    </el-steps>

    <component
      v-loading="form.loading"
      v-for="v of state.steps[state.businessTypeId]"
      :is="v.component"
      v-show="active===v.active"
      :isActive="active===v.active"
      :form.sync="form"
      :ref="'formRef'+v.active"
      :key="v.component"
    />

    <template #footer>
      <el-button @click="() => { form.show = false }">
        取 消
      </el-button>
      <el-button :disabled="active===0" @click="active--">上一步</el-button>
      <el-button
        :disabled="isLastStep"
        v-show="form.status==='r'||!isLastStep"
        @click="nextStep"
      >
        下一步
      </el-button>
      <template v-if="form.status!=='r'&&!form.loading">
        <el-button
          type="primary"
          @click="submit"
          :loading="form.submitting"
          v-if="isLastStep"
        >
          提 交
        </el-button>
      </template>
    </template>
  </KiFormDialog>
</template>

<script>
import { pickDeepBy } from '@/utils'
import { state, mutations } from '../store'
import ENUMS from '../enums'
import { mapGetters } from 'vuex'
import './modules/index.scss'
import { ENABLED_VALUE } from '@/utils/init'

const components = {}
const modules = import.meta.glob('./modules/*.vue', { eager: true })
for (const k in modules) {
  components[modules[k].default.name] = modules[k].default
}

export default {
  components,
  props: {
    form: {
      type: Object,
      required: false,
    },
    formTitle: {
      type: String,
    },
    submitForm: {
      type: Function,
    },
  },
  data () {
    return {
      active: 0,
      state,
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    isLastStep () {
      return this.active === state.steps[state.businessTypeId].length - 1
    },
  },
  watch: {
    'active' (n) {
      if (this.form.status === 'r') {
        this.clearValidate(n)
      }
      // 切换步骤时返回顶部
      this.$nextTick(() => {
        // 判空原因：active 不为0时关闭弹框也会触发
        this.getFormRef(n)?.$el.firstChild?.scrollIntoView({ behavior: 'smooth', block: 'center' })
      })
    },
    // 规则：库存类型存在几种形式
    // 1. 关闭原价显示 - 清空originalCost字段
    'form.data.openOriginalCost': {
      handler (type) {
        if (type === this.$enum.ENUM_COMMODITY_SWITCH_PRICE_TYPE[1].value) {
          this.$set(this.form.data, 'originalCost', undefined)
        }
      },
      deep: true
    },

    // 规则：库存类型存在几种形式
    // 1. 无限库存 - 清空总限量库存，清空日限量库存
    // 2. 日限量库存 - 清空总限量库存
    // 3. 总限量库存 - 清空日限量库存
    'form.data.repertoryType': {
      handler (type) {
        // 无限库存
        if (type === this.$enum.ENUM_COMMODITY_STOCK_TYPE[0].value) {
          this.$set(this.form.data, 'stockDayNum', undefined)
          this.$set(this.form.data, 'productTotal', undefined)
          return
        }
        // 总限量库存
        if (type === this.$enum.ENUM_COMMODITY_STOCK_TYPE[1].value) {
          this.$set(this.form.data, 'stockDayNum', undefined)
          return
        }

        // 日限量库存
        if (type === this.$enum.ENUM_COMMODITY_STOCK_TYPE[2].value) {
          this.$set(this.form.data, 'productTotal', undefined)
        }
      },
      deep: true
    },
    // 规则：奖励金存在几种形式
    // 1. 无奖励金
    // 2. 百分比奖励金
    // 3. 具体金额奖励金
    'form.data.exitDistr': {
      handler (type) {
        // 无奖励金
        if (type === this.$enum.ENUM_COMMODITY_SHARE_REWARDS_SWITCH_TYPE[0].value) {
          this.$set(this.form.data, 'calculationRewards', undefined) // 奖励金规则清空
          this.$set(this.form.data, 'distributionRewards', undefined) // 百分比奖励金清空
          this.$set(this.form.data, 'rewardsAmount', undefined) // 具体金额奖励金
        }
      },
      deep: true
    },
    'form.data.calculationRewards': {
      handler (type) {
        // 百分比奖励
        if (type === this.$enum.ENUM_COMMODITY_SHARE_REWARDS_RULER_TYPE[0].value) {
          this.$set(this.form.data, 'rewardsAmount', undefined) // 具体金额奖励金清空
          return
        }

        // 具体金额奖励金
        if (type === this.$enum.ENUM_COMMODITY_SHARE_REWARDS_RULER_TYPE[1].value) {
          this.$set(this.form.data, 'distributionRewards', undefined) // 百分比奖励清空
        }
      },
      deep: true
    },
  },
  created () {
    // 获取商铺列表
    const loading = this.$loading()
    this.$POST('/sot-admin-api/merchant/sub/queryListForMch', {
      status: ENABLED_VALUE, // 启用状态
      merchantId: this.userInfo.merchantId // 主商户id
    }).then(({ data }) => {
      mutations.updateOptions(data, 'subMerchant')
    }).finally(_ => {
      loading.close()
    })

    switch (state.businessTypeId) {
      // 获取票务平台出票方
      case '1':
        const loading = this.$loading()
        this.$POST(ENUMS.ENUM_URL_PREFIX['1'] + '/queryTicketChannelList').then(({ data }) => {
          mutations.updateOptions(data, 'ticketChannel')
        }).finally(() => {
          loading.close()
        })
        break
    }
  },
  methods: {
    onClosed () {
      this.active = 0
      mutations.resetStepStatus()
      this.$emit('closed')
    },
    getFormRef (i) {
      // 判空原因：切换步骤时返回顶部这个功能在 active 不为0时关闭弹框也会触发
      return this.$refs[`formRef${i}`][0]?.$refs.formRef
    },
    validate (active = this.active) {
      return new Promise((resolve, reject) => {
        this.getFormRef(active).validate().then(() => {
          mutations.updateStepStatus('success', active)
          resolve()
        }).catch(() => {
          mutations.updateStepStatus('error', active)
          reject()
        })
      })
    },
    clearValidate (active = this.active) {
      this.$nextTick(() => {
        this.getFormRef(active).clearValidate()
      })
    },
    clearAllValidate () {
      Array.from(Array(state.steps[state.businessTypeId].length)).map((v, i) => {
        this.clearValidate(i)
      })
    },
    validateAll () {
      return Promise.all(Array.from(Array(state.steps[state.businessTypeId].length)).map((v, i) => new Promise((resolve, reject) => {
        this.validate(i).then(() => {
          resolve()
        }).catch(() => {
          reject(i)
        })
      })))
    },
    nextStep () {
      if (this.form.status === 'r') {
        this.active++
      } else {
        this.validate().then(() => {
          this.active++
        }).catch(() => {
          this.$refs.kiFormDialogRef.highlightError()
        })
      }
    },
    submit () {
      this.form.submitting = true
      this.validateAll().then(() => {
        mutations.updateStepStatus('success', this.active)

        // 不可预定日期的值不能为空字符串，否则接口会报参数错误
        if (this.form.data.unavailableDates === '') {
          delete this.form.data.unavailableDates
        }

        this.submitForm(pickDeepBy(this.form.data, (v, k) =>
          ![NaN, null, undefined].includes(v) && !k.startsWith('__')
        ))
      }).catch(i => {
        this.active = i
        this.$refs.kiFormDialogRef.highlightError()
        this.form.submitting = false
      })
    },
  }
}
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  height: calc(100vh - 100px);
}

.el-steps {
  position: sticky;
  top: -25px;
  margin-top: -25px;
  margin-bottom: 20px;
  z-index: 2; // 高于“必填项”
  background: white;

  :deep(.el-step__icon) {
    cursor: pointer;
  }
}

.el-form {
  .el-select {
    width: 100%;
  }

  h3 {
    position: relative;

    &:before {
      position: absolute;
      top: 2.2px;
      left: -10px;
      content: '';
      width: 4px;
      height: 1rem;
      background-color: rgba(0, 204, 51, 1);
      border-radius: 4px;
    }
  }
}
</style>
